<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>服务端管理 - 即时通信系统</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2196F3, #1976D2);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 1.8em;
            margin-bottom: 10px;
        }
        
        .status {
            font-size: 0.9em;
            opacity: 0.9;
            transition: all 0.3s ease;
        }
        
        .status.connecting {
            color: #ffc107;
        }
        
        .status.connected {
            color: #28a745;
        }
        
        .status.disconnected {
            color: #dc3545;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            padding: 30px;
        }
        
        .section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
        }
        
        .section-title {
            font-size: 1.3em;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .section-title .badge {
            background: #2196F3;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8em;
        }
        
        .input-group {
            margin-bottom: 15px;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        
        .input-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s;
        }
        
        .input-group input:focus {
            outline: none;
            border-color: #2196F3;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 0.9em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #2196F3, #1976D2);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(33, 150, 243, 0.3);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #f44336, #d32f2f);
            color: white;
        }
        
        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(244, 67, 54, 0.3);
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            color: white;
        }
        
        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.3);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
            box-shadow: none !important;
        }
        
        .connection-requests {
            max-height: 300px;
            overflow-y: auto;
            border: 2px solid #ddd;
            border-radius: 8px;
            background: white;
            padding: 10px;
        }
        
        .request-item {
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }
        
        .request-item:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .request-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .request-info {
            flex: 1;
        }
        
        .request-name {
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }
        
        .request-time {
            font-size: 0.8em;
            color: #666;
        }
        
        .request-actions {
            display: flex;
            gap: 5px;
        }
        
        .request-actions .btn {
            padding: 5px 10px;
            font-size: 0.8em;
            margin: 0;
        }
        
        .no-requests {
            text-align: center;
            color: #666;
            padding: 20px;
            font-style: italic;
        }
        
        /* 聊天弹窗样式 */
        .chat-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }
        
        .chat-modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .chat-window {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            animation: slideIn 0.3s ease;
        }
        
        .chat-header {
            background: linear-gradient(135deg, #2196F3, #1976D2);
            color: white;
            padding: 15px 20px;
            border-radius: 15px 15px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .chat-header h3 {
            margin: 0;
            font-size: 1.2em;
        }
        
        .close-btn {
            background: none;
            border: none;
            color: white;
            font-size: 1.5em;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.3s;
        }
        
        .close-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .chat-body {
            flex: 1;
            padding: 20px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        .chat-messages {
            flex: 1;
            border: 2px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            overflow-y: auto;
            background: #fafafa;
            margin-bottom: 15px;
            max-height: 400px;
        }
        
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 8px;
            max-width: 80%;
        }
        
        .message.system {
            background: #e3f2fd;
            color: #1976d2;
            text-align: center;
            margin: 10px auto;
        }
        
        .message.received {
            background: #f1f1f1;
            color: #333;
            align-self: flex-start;
        }
        
        .message.sent {
            background: #2196F3;
            color: white;
            align-self: flex-end;
            margin-left: auto;
        }
        
        .message-header {
            font-size: 0.8em;
            opacity: 0.7;
            margin-bottom: 5px;
        }
        
        .chat-input {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        .chat-input input {
            flex: 1;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 1em;
        }
        
        .chat-input input:focus {
            outline: none;
            border-color: #2196F3;
        }
        
        .chat-input .btn {
            margin: 0;
            padding: 12px 15px;
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-50px) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        /* 聊天按钮 */
        .chat-toggle-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2196F3, #1976D2);
            color: white;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(33, 150, 243, 0.3);
            transition: all 0.3s ease;
            z-index: 999;
        }
        
        .chat-toggle-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(33, 150, 243, 0.4);
        }
        
        .chat-toggle-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        .back-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            font-size: 1.5em;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
                padding: 20px;
            }
            
            .chat-window {
                width: 95%;
                max-height: 90vh;
            }
            
            .chat-toggle-btn {
                bottom: 20px;
                right: 20px;
                width: 50px;
                height: 50px;
                font-size: 1.2em;
            }
            
            .chat-input {
                flex-direction: column;
            }
            
            .chat-input .btn {
                width: 100%;
            }
        }
        
        .auto-connect-status {
            margin-top: 5px;
            font-size: 0.8em;
        }
        
        .auto-connect-status .badge {
            background: #28a745;
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.7em;
        }
        
        /* 在线管理员显示样式 */
        .online-admins-section {
            margin-top: 20px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        
        .online-admins-title {
            font-size: 1.1em;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .online-admins-container {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            min-height: 40px;
            align-items: center;
        }
        
        .admin-item {
            background: #e3f2fd;
            border: 2px solid #2196F3;
            border-radius: 20px;
            padding: 8px 15px;
            font-size: 0.9em;
            color: #1976d2;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .admin-item:hover {
            background: #2196F3;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(33, 150, 243, 0.3);
        }
        
        .admin-item.current {
            background: #4caf50;
            border-color: #4caf50;
            color: white;
        }
        
        .admin-item.current:hover {
            background: #45a049;
            box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3);
        }
        
        .admin-avatar {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: currentColor;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.7em;
            font-weight: bold;
        }
        
        .admin-tooltip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: #333;
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 0.8em;
            white-space: nowrap;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            margin-bottom: 5px;
        }
        
        .admin-tooltip::after {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            border: 5px solid transparent;
            border-top-color: #333;
        }
        
        .admin-item:hover .admin-tooltip {
            opacity: 1;
            visibility: visible;
        }
        
        .no-admins {
            color: #666;
            font-style: italic;
            text-align: center;
            width: 100%;
        }
    </style>
</head>
<body>
    <button class="back-btn" onclick="window.location.href='http://10.8.20.95:8080/'">←</button>
    
    <div class="container">
        <div class="header">
            <h1>服务端管理</h1>
            <div class="status" id="connectionStatus">正在初始化...</div>
            <div class="auto-connect-status" id="autoConnectStatus" style="display: none;">
                <span class="badge badge-success">自动连接已启用</span>
            </div>
        </div>
        
        <div class="main-content">
            <div class="section">
                <div class="section-title">
                    连接管理
                    <span class="badge" id="adminId">未设置</span>
                </div>
                
                <div class="input-group">
                    <label for="adminName">服务端用户ID：</label>
                    <input type="text" id="adminName" placeholder="请输入您的ID" value="管理员">
                </div>
                
                <div class="connection-status" id="statusDisplay">
                    <span id="statusText">未连接</span>
                </div>
                
                <button class="btn btn-primary" id="connectBtn" onclick="connectAsAdmin()">
                    连接为服务端用户
                </button>
                <button class="btn btn-secondary" id="disconnectBtn" onclick="disconnect()" disabled>
                    断开连接
                </button>
                <button class="btn btn-secondary" onclick="checkServiceStatus()">
                    检查服务状态
                </button>
                <button class="btn btn-secondary" onclick="forceReconnect()">
                    强制重连
                </button>
                
                <div class="stats-grid" id="statsGrid" style="display: none;">
                    <div class="stat-card">
                        <div class="stat-value" id="totalRequests">0</div>
                        <div class="stat-label">总请求数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="queueSize">0</div>
                        <div class="stat-label">队列中</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="activeConnections">0</div>
                        <div class="stat-label">活跃连接</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="adminCount">0</div>
                        <div class="stat-label">在线管理员</div>
                    </div>
                </div>
                
                <!-- 在线管理员显示区域 -->
                <div class="online-admins-section" id="onlineAdminsSection" style="display: none;">
                    <div class="online-admins-title">
                        <span>👥 在线管理员</span>
                        <span class="badge" id="onlineAdminCount">0</span>
                    </div>
                    <div class="online-admins-container" id="onlineAdminsContainer">
                        <div class="no-admins">暂无在线管理员</div>
                    </div>
                </div>
            </div>
            
            <div class="section">
                <div class="section-title">
                    连接请求
                    <span class="badge" id="requestCount">0</span>
                </div>
                
                <div class="connection-requests" id="connectionRequests">
                    <div class="no-requests">暂无连接请求</div>
                </div>
            </div>
        </div>
        
        <!-- 聊天弹窗 -->
        <div class="chat-modal" id="chatModal">
            <div class="chat-window">
                <div class="chat-header">
                    <h3>聊天窗口</h3>
                    <button class="close-btn" onclick="closeChatWindow()">×</button>
                </div>
                <div class="chat-body">
                    <div class="chat-messages" id="chatMessages">
                        <div class="message system">
                            等待连接建立...
                        </div>
                    </div>
                    <div class="chat-input">
                        <input type="text" id="messageInput" placeholder="输入消息..." onkeypress="handleKeyPress(event)">
                        <button class="btn btn-primary" onclick="sendMessage()">发送</button>
                        <button class="btn btn-danger" onclick="releaseConnection()">释放连接</button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 聊天按钮 -->
        <button class="chat-toggle-btn" id="chatToggleBtn" onclick="toggleChatWindow()" disabled>
            💬
        </button>
    </div>
    
    <script>
        let socket = null;
        let isConnected = false;
        let currentClientId = null;
        let adminId = null;
        let connectionRequests = [];
        let reconnectAttempts = 0;
        let maxReconnectAttempts = 10;
        let reconnectInterval = null;
        let heartbeatInterval = null;
        let autoConnectEnabled = false; // 自动连接开关
        let onlineAdmins = []; // 在线管理员列表
        let isChatWindowOpen = false;
        
        // 初始化WebSocket连接
        function initWebSocket() {
            // 检查是否有保存的管理员ID
            const savedAdminId = localStorage.getItem('adminId');
            if (savedAdminId) {
                console.log('发现保存的管理员ID:', savedAdminId);
                adminId = savedAdminId;
                document.getElementById('adminName').value = adminId;
                document.getElementById('adminId').textContent = adminId;
                
                // 检查服务是否可用，然后再自动连接
                checkServiceAvailability().then(available => {
                    if (available) {
                        console.log('服务可用，开始自动连接');
                        autoConnectEnabled = true;
                        establishConnection();
                    } else {
                        console.log('服务不可用，等待手动连接');
                        autoConnectEnabled = false;
                        updateStatus('disconnected', '服务不可用，请手动连接');
                        document.getElementById('connectionStatus').textContent = '服务不可用';
                    }
                }).catch(error => {
                    console.log('检查服务可用性失败:', error);
                    autoConnectEnabled = false;
                    updateStatus('disconnected', '服务检查失败，请手动连接');
                    document.getElementById('connectionStatus').textContent = '服务检查失败';
                });
            } else {
                // 如果没有保存的ID，不自动连接，等待用户手动输入
                console.log('没有保存的管理员ID，等待手动连接');
                autoConnectEnabled = false;
                updateStatus('disconnected', '请输入ID并手动连接');
                document.getElementById('connectionStatus').textContent = '等待连接';
            }
        }
        
        // 检查服务是否可用
        function checkServiceAvailability() {
            return new Promise((resolve, reject) => {
                const timeout = setTimeout(() => {
                    reject(new Error('服务检查超时'));
                }, 5000); // 5秒超时
                
                fetch('http://10.8.20.95:8080/api/stats', {
                    method: 'GET',
                    mode: 'cors'
                })
                .then(response => {
                    clearTimeout(timeout);
                    if (response.ok) {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                })
                .catch(error => {
                    clearTimeout(timeout);
                    console.log('服务检查失败:', error);
                    resolve(false);
                });
            });
        }
        
        // 手动检查服务状态
        function checkServiceStatus() {
            console.log('手动检查服务状态...');
            document.getElementById('connectionStatus').textContent = '检查服务状态中...';
            
            checkServiceAvailability().then(available => {
                if (available) {
                    console.log('服务可用');
                    document.getElementById('connectionStatus').textContent = '服务可用';
                    alert('服务状态正常，可以连接');
                    
                    // 如果当前未连接且启用了自动连接，尝试连接
                    if (!isConnected && autoConnectEnabled && adminId) {
                        console.log('尝试自动连接');
                        reconnectAttempts = 0; // 重置重连次数
                        establishConnection();
                    }
                } else {
                    console.log('服务不可用');
                    document.getElementById('connectionStatus').textContent = '服务不可用';
                    alert('服务不可用，请检查服务器状态');
                }
            }).catch(error => {
                console.log('服务检查失败:', error);
                document.getElementById('connectionStatus').textContent = '服务检查失败';
                alert('服务检查失败: ' + error.message);
            });
        }
        
        // 强制重连
        function forceReconnect() {
            console.log('强制重连...');
            
            // 停止所有定时器
            stopHeartbeat();
            if (reconnectInterval) {
                clearInterval(reconnectInterval);
                reconnectInterval = null;
            }
            
            // 重置状态
            isConnected = false;
            currentClientId = null;
            closeChatWindow();
            hideStats();
            
            // 关闭现有连接
            if (socket) {
                socket.close();
                socket = null;
            }
            
            // 调用服务端清理会话API
            fetch('http://10.8.20.95:8080/api/clear-sessions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response => response.json())
            .then(data => {
                console.log('服务端会话清理结果:', data);
            })
            .catch(error => {
                console.log('清理会话API调用失败:', error);
            });
            
            // 重置重连次数
            reconnectAttempts = 0;
            
            // 延迟重新连接
            setTimeout(() => {
                console.log('开始强制重连...');
                document.getElementById('connectionStatus').textContent = '正在强制重连...';
                establishConnection();
            }, 2000);
        }
        
        // 处理接收到的消息
        function handleMessage(message) {
            console.log('收到消息:', message);
            console.log('消息类型:', message.type);
            console.log('消息内容:', message.content);
            console.log('消息来源:', message.from);
            console.log('会话ID:', message.sessionId);
            
            switch(message.type) {
                case 'SYSTEM_MESSAGE':
                    // 过滤掉其他服务端用户处理连接请求的消息
                    if (message.content && shouldFilterSystemMessage(message.content)) {
                        console.log('过滤掉系统消息:', message.content);
                        return; // 不显示在聊天框中
                    }
                    addSystemMessage(message.content);
                    break;
                    
                case 'CONNECT_REQUEST':
                    console.log('处理连接请求:', message);
                    addConnectionRequest(message);
                    break;
                    
                case 'REMOVE_REQUEST':
                    console.log('处理移除请求:', message);
                    removeRequest(message.sessionId);
                    // 不显示移除请求的系统消息，因为已经在上面过滤了
                    break;
                    
                case 'CHAT_MESSAGE':
                    addChatMessage(message.content, message.from, false);
                    break;
                    
                case 'ONLINE_ADMINS':
                    console.log('处理在线管理员信息:', message);
                    updateOnlineAdmins(message.admins || []);
                    break;
                    
                default:
                    console.log('未知消息类型:', message.type);
            }
        }
        
        // 判断是否应该过滤系统消息
        function shouldFilterSystemMessage(content) {
            // 过滤掉其他服务端用户处理连接请求的消息
            if (content.includes('的连接已被') && 
                !content.includes('您已') &&
                !content.includes('欢迎服务端用户')) {
                return true;
            }
            
            // 过滤掉其他服务端用户拒绝连接的消息
            if (content.includes('的连接已被') && 
                content.includes('拒绝') &&
                !content.includes('您已')) {
                return true;
            }
            
            // 过滤掉"连接已被处理"的消息（这些是REMOVE_REQUEST消息，不需要显示）
            if (content.includes('的连接已被处理')) {
                return true;
            }
            
            return false;
        }
        
        // 作为服务端用户连接
        function connectAsAdmin() {
            const name = document.getElementById('adminName').value.trim();
            if (!name) {
                alert('请输入服务端用户ID');
                return;
            }
            
            adminId = name;
            document.getElementById('adminId').textContent = adminId;
            
            // 保存管理员ID到本地存储
            localStorage.setItem('adminId', adminId);
            autoConnectEnabled = true;
            
            // 建立新的WebSocket连接，带上管理员参数
            establishConnection();
        }
        
        // 建立WebSocket连接
        function establishConnection() {
            if (socket) {
                socket.close();
            }
            
            console.log('建立WebSocket连接...');
            document.getElementById('connectionStatus').textContent = '正在连接...';
            updateStatus('disconnected', '正在连接...');
            
            socket = new SockJS(`http://10.8.20.95:8080/ws?type=admin&id=${encodeURIComponent(adminId)}`);
            
            socket.onopen = function() {
                console.log('WebSocket连接已建立');
                reconnectAttempts = 0; // 重置重连次数
                updateStatus('connected', '已连接为服务端用户');
                document.getElementById('connectionStatus').textContent = '已连接';
                isConnected = true;
                showStats();
                loadStats();
                
                // 启动心跳机制
                startHeartbeat();
                
                // 清除重连定时器
                if (reconnectInterval) {
                    clearInterval(reconnectInterval);
                    reconnectInterval = null;
                }
            };
            
            socket.onmessage = function(event) {
                const message = JSON.parse(event.data);
                handleMessage(message);
            };
            
            socket.onclose = function(event) {
                console.log('WebSocket连接关闭:', event);
                updateStatus('disconnected', '连接已断开，正在重连...');
                document.getElementById('connectionStatus').textContent = '连接断开，重连中...';
                isConnected = false;
                currentClientId = null;
                closeChatWindow();
                hideStats();
                
                // 停止心跳
                stopHeartbeat();
                
                // 自动重连
                if (adminId && autoConnectEnabled) {
                    scheduleReconnect();
                }
            };
            
            socket.onerror = function(error) {
                console.error('WebSocket连接错误:', error);
                updateStatus('disconnected', '连接错误，正在重连...');
                document.getElementById('connectionStatus').textContent = '连接错误，重连中...';
            };
        }
        
        // 安排重连
        function scheduleReconnect() {
            if (!autoConnectEnabled) {
                console.log('自动连接已禁用，不进行重连');
                return;
            }
            
            if (reconnectInterval) {
                clearInterval(reconnectInterval);
            }
            
            reconnectAttempts++;
            const delay = Math.min(1000 * Math.pow(2, reconnectAttempts - 1), 30000); // 指数退避，最大30秒
            
            console.log(`安排重连，第${reconnectAttempts}次尝试，延迟${delay}ms`);
            
            reconnectInterval = setTimeout(async () => {
                if (reconnectAttempts <= maxReconnectAttempts && autoConnectEnabled) {
                    console.log(`执行重连，第${reconnectAttempts}次尝试`);
                    
                    // 先检查服务是否可用
                    try {
                        const available = await checkServiceAvailability();
                        if (available) {
                            console.log('服务可用，开始重连');
                            establishConnection();
                        } else {
                            console.log('服务不可用，继续等待重连');
                            // 如果服务不可用，继续安排重连
                            scheduleReconnect();
                        }
                    } catch (error) {
                        console.log('服务检查失败，继续重连:', error);
                        // 如果检查失败，也继续重连
                        scheduleReconnect();
                    }
                } else if (reconnectAttempts > maxReconnectAttempts) {
                    console.error('重连次数超过限制，停止重连');
                    document.getElementById('connectionStatus').textContent = '连接失败，请刷新页面';
                    updateStatus('disconnected', '连接失败，请刷新页面重试');
                    autoConnectEnabled = false;
                }
            }, delay);
        }
        
        // 启动心跳机制
        function startHeartbeat() {
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
            }
            
            heartbeatInterval = setInterval(() => {
                if (socket && socket.readyState === 1) {
                    try {
                        socket.send(JSON.stringify({
                            type: 'HEARTBEAT',
                            timestamp: Date.now()
                        }));
                    } catch (error) {
                        console.error('发送心跳失败:', error);
                    }
                }
            }, 30000); // 每30秒发送一次心跳
        }
        
        // 停止心跳机制
        function stopHeartbeat() {
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
                heartbeatInterval = null;
            }
        }
        
        // 断开连接
        function disconnect() {
            if (confirm('确定要断开连接吗？断开后将停止自动重连。')) {
                if (socket) {
                    // 停止心跳和重连
                    stopHeartbeat();
                    if (reconnectInterval) {
                        clearInterval(reconnectInterval);
                        reconnectInterval = null;
                    }
                    
                    socket.close();
                    adminId = null;
                    reconnectAttempts = 0;
                    autoConnectEnabled = false;
                    
                    // 清除保存的管理员ID
                    localStorage.removeItem('adminId');
                    
                    updateStatus('disconnected', '未连接');
                    document.getElementById('connectionStatus').textContent = '未连接';
                    document.getElementById('adminName').value = '';
                    document.getElementById('adminId').textContent = '';
                }
            }
        }
        
        // 接受连接请求
        function acceptRequest(clientSessionId) {
            if (!isConnected) {
                alert('请先连接为服务端用户');
                return;
            }
            
            const message = {
                type: 'CONNECT_REQUEST',
                sessionId: clientSessionId,
                content: 'accept'
            };
            
            socket.send(JSON.stringify(message));
            currentClientId = clientSessionId;
            openChatWindow();
            
            // 立即从本地移除请求，不等待服务器响应
            removeRequest(clientSessionId);
        }
        
        // 拒绝连接请求
        function rejectRequest(clientSessionId) {
            if (!isConnected) {
                alert('请先连接为服务端用户');
                return;
            }
            
            const message = {
                type: 'CONNECT_REQUEST',
                sessionId: clientSessionId,
                content: 'reject'
            };
            
            socket.send(JSON.stringify(message));
            
            // 立即从本地移除请求，不等待服务器响应
            removeRequest(clientSessionId);
        }
        
        // 释放连接
        function releaseConnection() {
            if (!currentClientId) {
                alert('当前没有活跃连接');
                return;
            }
            
            const message = {
                type: 'CONNECT_RELEASE',
                content: 'release'
            };
            
            socket.send(JSON.stringify(message));
            currentClientId = null;
            closeChatWindow();
        }
        
        // 发送消息
        function sendMessage() {
            if (!currentClientId) {
                alert('当前没有活跃连接，无法发送消息');
                return;
            }
            
            const input = document.getElementById('messageInput');
            const content = input.value.trim();
            
            if (!content) {
                return;
            }
            
            const message = {
                type: 'CHAT_MESSAGE',
                from: adminId,
                content: content
            };
            
            socket.send(JSON.stringify(message));
            addChatMessage(content, '我', true);
            input.value = '';
        }
        
        // 处理回车键
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }
        
        // 更新状态显示
        function updateStatus(status, text) {
            const statusDisplay = document.getElementById('statusDisplay');
            const statusText = document.getElementById('statusText');
            const connectBtn = document.getElementById('connectBtn');
            const disconnectBtn = document.getElementById('disconnectBtn');
            const chatToggleBtn = document.getElementById('chatToggleBtn');
            const autoConnectStatus = document.getElementById('autoConnectStatus');
            
            statusDisplay.className = 'connection-status status-' + status;
            statusText.textContent = text;
            
            // 显示自动连接状态
            if (autoConnectEnabled) {
                autoConnectStatus.style.display = 'block';
            } else {
                autoConnectStatus.style.display = 'none';
            }
            
            switch(status) {
                case 'disconnected':
                    connectBtn.disabled = false;
                    disconnectBtn.disabled = true;
                    chatToggleBtn.disabled = true;
                    break;
                case 'connected':
                    connectBtn.disabled = true;
                    disconnectBtn.disabled = false;
                    chatToggleBtn.disabled = false;
                    break;
            }
        }
        
        // 显示统计信息
        function showStats() {
            document.getElementById('statsGrid').style.display = 'grid';
        }
        
        // 隐藏统计信息
        function hideStats() {
            document.getElementById('statsGrid').style.display = 'none';
        }
        
        // 加载统计信息
        function loadStats() {
            fetch('http://10.8.20.95:8080/api/stats')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('totalRequests').textContent = data.totalRequests;
                    document.getElementById('queueSize').textContent = data.queueSize;
                    document.getElementById('activeConnections').textContent = data.activeConnections;
                    document.getElementById('adminCount').textContent = data.adminCount;
                })
                .catch(error => console.error('加载统计信息失败:', error));
        }
        
        // 添加连接请求
        function addConnectionRequest(message) {
            // 检查是否已存在相同的请求
            const existingRequest = connectionRequests.find(req => req.sessionId === message.sessionId);
            if (existingRequest) {
                console.log('连接请求已存在，跳过添加:', message.sessionId);
                return;
            }
            
            const request = {
                sessionId: message.sessionId,
                name: message.from,
                time: new Date().toLocaleTimeString(),
                content: message.content
            };
            
            console.log('添加新的连接请求:', request);
            connectionRequests.push(request);
            updateRequestDisplay();
        }
        
        // 移除连接请求
        function removeRequest(sessionId) {
            console.log('移除连接请求:', sessionId);
            const originalLength = connectionRequests.length;
            connectionRequests = connectionRequests.filter(req => req.sessionId !== sessionId);
            const removedCount = originalLength - connectionRequests.length;
            console.log(`移除了 ${removedCount} 个连接请求`);
            updateRequestDisplay();
        }
        
        // 更新请求显示
        function updateRequestDisplay() {
            const container = document.getElementById('connectionRequests');
            const countBadge = document.getElementById('requestCount');
            
            countBadge.textContent = connectionRequests.length;
            
            if (connectionRequests.length === 0) {
                container.innerHTML = '<div class="no-requests">暂无连接请求</div>';
                return;
            }
            
            container.innerHTML = connectionRequests.map(request => `
                <div class="request-item">
                    <div class="request-header">
                        <div class="request-name">${request.name}</div>
                        <div class="request-time">${request.time}</div>
                    </div>
                    <div class="request-actions">
                        <button class="btn btn-success" onclick="acceptRequest('${request.sessionId}')">
                            接受
                        </button>
                        <button class="btn btn-danger" onclick="rejectRequest('${request.sessionId}')">
                            拒绝
                        </button>
                    </div>
                </div>
            `).join('');
        }
        
        // 添加系统消息
        function addSystemMessage(content) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message system';
            messageDiv.textContent = content;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 添加聊天消息
        function addChatMessage(content, sender, isSent) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isSent ? 'sent' : 'received'}`;
            
            const headerDiv = document.createElement('div');
            headerDiv.className = 'message-header';
            headerDiv.textContent = sender + ' - ' + new Date().toLocaleTimeString();
            
            const contentDiv = document.createElement('div');
            contentDiv.textContent = content;
            
            messageDiv.appendChild(headerDiv);
            messageDiv.appendChild(contentDiv);
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 更新在线管理员显示
        function updateOnlineAdmins(admins) {
            onlineAdmins = admins;
            const container = document.getElementById('onlineAdminsContainer');
            const countElement = document.getElementById('onlineAdminCount');
            const section = document.getElementById('onlineAdminsSection');
            
            // 更新数量
            countElement.textContent = admins.length;
            
            // 显示区域
            section.style.display = 'block';
            
            // 清空容器
            container.innerHTML = '';
            
            if (admins.length === 0) {
                container.innerHTML = '<div class="no-admins">暂无在线管理员</div>';
                return;
            }
            
            // 添加管理员项
            admins.forEach(admin => {
                const adminItem = document.createElement('div');
                adminItem.className = 'admin-item';
                if (admin === adminId) {
                    adminItem.classList.add('current');
                }
                
                // 获取管理员名字的首字母作为头像
                const avatarText = admin.charAt(0).toUpperCase();
                
                adminItem.innerHTML = `
                    <div class="admin-avatar">${avatarText}</div>
                    <span>${admin}</span>
                    <div class="admin-tooltip">管理员: ${admin}</div>
                `;
                
                container.appendChild(adminItem);
            });
        }
        
        // 页面可见性变化处理
        function handleVisibilityChange() {
            if (document.hidden) {
                console.log('页面隐藏，暂停部分功能');
            } else {
                console.log('页面可见，恢复功能');
                if (isConnected) {
                    loadStats();
                } else if (autoConnectEnabled && adminId) {
                    // 页面恢复时，如果之前是自动连接模式，先检查服务是否可用
                    console.log('页面恢复，检查服务可用性');
                    checkServiceAvailability().then(available => {
                        if (available) {
                            console.log('服务可用，尝试重新连接');
                            reconnectAttempts = 0; // 重置重连次数
                            establishConnection();
                        } else {
                            console.log('服务不可用，不进行重连');
                        }
                    }).catch(error => {
                        console.log('服务检查失败，不进行重连:', error);
                    });
                }
            }
        }
        
        // 定期刷新统计信息
        function startStatsRefresh() {
            setInterval(() => {
                if (isConnected && !document.hidden) {
                    loadStats();
                }
            }, 5000);
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('服务端页面初始化...');
            
            // 检查是否是页面刷新
            const isPageRefresh = performance.navigation.type === 1 || 
                                (window.performance && window.performance.getEntriesByType('navigation')[0] && 
                                 window.performance.getEntriesByType('navigation')[0].type === 'reload');
            
            if (isPageRefresh) {
                console.log('检测到页面刷新，清理可能的状态残留...');
                
                // 清理localStorage中可能的状态
                localStorage.removeItem('adminConnected');
                localStorage.removeItem('adminId');
                localStorage.removeItem('autoConnectEnabled');
                
                // 清理sessionStorage
                sessionStorage.clear();
                
                // 重置页面状态
                isConnected = false;
                currentClientId = null;
                reconnectAttempts = 0;
                
                // 延迟初始化，确保清理完成
                setTimeout(() => {
                    initWebSocket();
                }, 500);
            } else {
                // 正常页面加载
                initWebSocket();
            }
            
            // 添加页面卸载时的清理
            window.addEventListener('beforeunload', function() {
                console.log('页面即将卸载，清理连接...');
                if (socket) {
                    socket.close();
                }
                stopHeartbeat();
                if (reconnectInterval) {
                    clearInterval(reconnectInterval);
                }
            });
            
            // 延迟执行其他初始化
            setTimeout(() => {
                updateStatus('disconnected', '正在连接...');
                
                // 监听页面可见性变化
                document.addEventListener('visibilitychange', handleVisibilityChange);
                
                // 启动统计信息自动刷新
                startStatsRefresh();
            }, 1000);
        });
        
        // 打开聊天窗口
        function openChatWindow() {
            const modal = document.getElementById('chatModal');
            modal.classList.add('show');
            isChatWindowOpen = true;
            // 聚焦到输入框
            setTimeout(() => {
                document.getElementById('messageInput').focus();
            }, 100);
        }
        
        // 关闭聊天窗口
        function closeChatWindow() {
            const modal = document.getElementById('chatModal');
            modal.classList.remove('show');
            isChatWindowOpen = false;
        }
        
        // 切换聊天窗口
        function toggleChatWindow() {
            if (isChatWindowOpen) {
                closeChatWindow();
            } else {
                openChatWindow();
            }
        }
        
        // 点击模态框背景关闭
        document.getElementById('chatModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeChatWindow();
            }
        });
    </script>
</body>
</html>
